/*
 * Copyright (c) 2011 Jean-Marc Perronne
 * Ensisa, 12 rue des Freres Lumieres, F-68093 Mulhouse cedex
 * All rights reserved.
 *
 * The copyright of this software is owned by Werner Randelshofer. 
 * You may not use, copy or modify this software, except in  
 * accordance with the license agreement you entered into with  
 * Jean-Marc Perronne. For details see accompanying license terms. 
 */

package fr.uha.ensisa.jmp.ui.model;

import java.util.ArrayList;
import java.util.List;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class DefaultBoundedModel implements BoundedModel
{
	private List<ChangeListener> listeners;
	private ChangeEvent changeEvent;

	private int min, max, value;

	public DefaultBoundedModel(int value, int min, int max)
	{
		this.listeners = new ArrayList<ChangeListener>();
		this.changeEvent = new ChangeEvent(this);

		this.checkRange(value, min, max);
		this.min = min;
		this.max = max;
		this.value = value;
	}

	public DefaultBoundedModel()
	{
		this(0, 0, 100);
	}

	private void checkRange(int value, int min, int max)
	{
		if ((max < min) || (value < min) || (value > max)) throw new IllegalArgumentException("invalid range properties");
	}

	@Override
	public void addChangeListener(ChangeListener l)
	{
		this.listeners.add(l);
	}

	@Override
	public void removeChangeListener(ChangeListener l)
	{
		this.listeners.remove(l);
	}
	
	protected void fireStateChanged()
	{
		for (ChangeListener l : this.listeners)
			l.stateChanged(changeEvent);
	}

	@Override
	public int getMaximum()
	{
		return this.max;
	}

	@Override
	public int getMinimum()
	{
		return this.min;
	}

	@Override
	public int getValue()
	{
		return this.value;
	}

	@Override
	public void setMaximum(int v)
	{
		this.checkRange(this.value, this.min, v);
		if (v != this.max)
		{
			this.max = v;
			this.fireStateChanged();
		}
	}

	@Override
	public void setMinimum(int v)
	{
		this.checkRange(this.value, v, this.max);
		if (v != this.min)
		{
			this.min = v;
			this.fireStateChanged();
		}
	}

	@Override
	public void setValue(int v)
	{
		this.checkRange(v, this.min, this.max);
		if (v != this.value)
		{
			this.value = v;
			this.fireStateChanged();
		}
	}

	
    public String toString()  {
        String modelString =
            "value=" + getValue() + ", " +
            "min=" + getMinimum() + ", " +
            "max=" + getMaximum();

        return getClass().getName() + "[" + modelString + "]";
    }

}
